Using MongoDB Low Level Query In Grails | Aggregation Framework

Posted By : Amit Kumar | 28-Jul-2014

 

Using MongoDB Low Level Query In Grails | MongoDB Aggregation

 

Continue from previous blog , where we have discussed about the native MongoDB CRUD operation through grails , now its time to go into dipper 'MongoDB Aggregation Framework', which lets you to manage complex data from database and we can have computed results, same as we used in any SQL database.


The main advantage of using MongoDB Aggregation Framework in Grails:

1.) Used to solve complex data in collections

2.) Grouping mechanism is there

3.) Data processing pipelines supports

4.) Internal optimization operations supports

 


Note :

Grails Version : 2.3.6

MongoDB Version : mongodb:2.0.1

 


In this tutorial we will have look on Aggregation operation through Grails MongoDB Native Query. I will use Employee Domain as example.

Code Snippet :- Employee.groovy

 

class Employee{
	String name
	String address
}

Code Snippet :-

def match=['$match':['name':'ABC1']]
def push=['$push':'$$ROOT']
def group=['$group':['_id':'$name',count:['$sum':1],info:push]]
def project=['$project':['_id':0,'count':1,'info':1]]
def sort=['_id':1]
def outputResult=Employee.collection.aggregate(match, group, project, sort)
def resultArray= outputResult.results()


In above code, aggregation method has only one required parameter either $group or $match but i used other optional parameter. Here is detailed information of each.

$match

It is the where clause for aggreagtion

 


$group

Groups the data, based on single or composite field.

 


$sum

Used in $group block, it sums required field or we can count total no. of documents return in particular group.

 


$push

If we want any field from collection, to be in return results, we can use $push operation in $group block, but i used '$$ROOT' which means return all fields in results.

 


$project

We can eliminate fields from returned results. We can mark 1(visible) or 0(not-visible) in this block against any field

 


$sort

We can sort the data based on one field or based on multiple field.

 


Detailed information are available here Click

 

Hope it will help you.

 

Thanks

Amit

 

 

About Author

Author Image
Amit Kumar

Amit is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.

Request for Proposal

Name is required

Comment is required

Sending message..